package com.xy.novelweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xy.novelweb.domain.*;
import com.xy.novelweb.service.readers.ReaderService;
import com.xy.novelweb.utils.AlipayConfig;
import com.xy.novelweb.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.crypto.MacSpi;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@Slf4j
@RequestMapping("reader")
public class ReaderController {
		@Autowired
		private ReaderService readerService;

		@RequestMapping("getusermsg")
		public String getReaderAllMsg(HttpServletRequest request) {
				//从session获取用户名
				HttpSession session = request.getSession();
				Reader read_user = (Reader) session.getAttribute("user_reader");
				if (read_user == null) {
						return "redirect:/index";
				}
				String nick_name = read_user.getNickName();

				//根据用户名从数据库中查用用户的所有信息
				Reader reader = readerService.getReaderByName(nick_name);
				log.info("getReaderAllMsg:" + reader);
				request.setAttribute("readermsg", reader);
				return "reader";
		}

		public void emptyDir(String path) {
				File file = new File(path);
				for (File f : file.listFiles()) {
						log.info("[delete: imgfile ]=" + f.getName());
						f.delete();
				}

		}

		/*
		 * 图片上传
		 * */
		@ResponseBody
		@RequestMapping("imgupload")
		public Msg ImgUpLoad(HttpServletRequest request, @RequestParam(value = "file") MultipartFile multipartfile) {
				Msg msg = new Msg(true);
				MultipartFile multipartFile = multipartfile;
				Reader reader = (Reader) request.getSession().getAttribute("user_reader");
				List<String> urls = new ArrayList<>();

				if (!multipartFile.isEmpty()) {
						try {
								//1创建目录
								// 1.1 获取发布路径
								String username = reader.getNickName();
								String dir = "user-photo/" + username;
								//String dir = "D:/JavaFileBox/user-photo" +File.separator+ username;//D:/JavaFileBox/user-photo

								String targetDir = "D:/JavaFileBox/"+ "/" + dir;

								//1.3 创建path对象 File new File()-->Path  Paths.get() 新的对象
								Path targetDirFile = Paths.get(targetDir);

								//1.4 创建不存在的目录 如果上传的文件目录不存在就创建
								if (Files.notExists(targetDirFile)) {
										Files.createDirectories(targetDirFile);
								}
								emptyDir(targetDir);
								//2 获取上传文件的文件名
								String fileName = multipartFile.getOriginalFilename();

								// 3 保存到项目的服务器发布路径
								/*D:/NovelWebProject/src/main/webapp/static/user-photo/用户名/filename*/
								Path target = Paths.get(targetDir, fileName);//get(目标路径，文件名)

								//4 将数据写入文件
								multipartFile.transferTo(target.toFile());

								//5 将路径添加到urls中
								urls.add("wfRead/" + dir + File.separator + fileName);

								//设置用户头像
								//插入数据库
								int code = readerService.SetUserHeadImg(username, fileName);
								if (code == -1) {
										msg.setFlag(false);
										msg.setMessage("参数错误！请检查是否登录！");
								} else if (code == 0) {
										msg.setFlag(false);
										msg.setMessage("上传失败！请稍后重试！");
								} else {
										request.getSession().setAttribute("user_reader", readerService.getReaderByName(username));
								}
						} catch (Exception e) {
								log.error("错误消息：{}", e.getMessage(), e);
								msg.setFlag(false);
								msg.setMessage(e.getMessage());
						}
						msg.setMessage("上传成功");
						msg.setData(urls);
				} else {
						msg.setFlag(false);
						msg.setMessage("上传文件为空！请检查后重试！");
				}
				log.info("ImgUpLoad:" + msg);
				return msg;
		}

		/*
		 * 用户信息修改
		 *
		 * */
		@ResponseBody
		@RequestMapping("updatareader")
		public Msg updataReader(HttpServletRequest request) {
				Msg msg = new Msg(true);
				Reader reader = new Reader();
				try {
						String nick_name = request.getParameter("nick_name");
						String sex = request.getParameter("sex");
						String birthStr = request.getParameter("birthday");
						String pattern = "\\d{4}-\\d{1,2}-\\d{1,2}";
						Date birthday = null;
						String address = request.getParameter("address");
						String intro = request.getParameter("intro");

						int flag = 0;
						Map<String, String> erroField = new HashMap<String, String>();
						// 创建 Pattern 对象
						Pattern r = Pattern.compile(pattern);
						// 现在创建 matcher 对象
						Matcher m = r.matcher(birthStr);
						if (m.find()) {
								birthday = new SimpleDateFormat("yyyy-MM-dd").parse(birthStr);
						} else {
								erroField.put("birthday", "输入生日格式有误!应为yyyy-MM-dd格式！");
						}
						if (nick_name == null || "".equals(nick_name)) {
								erroField.put("nick_name", "昵称不能为空！");
						}
						if (intro.length() >= 100) {
								erroField.put("intro", "简介长度不能超过100");
						}
						if (address.length() >= 200) {
								erroField.put("address", "地址长度不能超过200");
						}
						if (erroField.isEmpty()) {
								reader.setNickName(nick_name);
								reader.setSex(sex);
								reader.setBirthday(birthday);
								reader.setIntro(intro);
								reader.setAddress(address);
								flag = readerService.UpdateReaderMsg(reader);
						}
						if (flag == 1) {
								msg.setFlag(true);
						} else {
								msg.setFlag(false);
								msg.setFieldErrers(erroField);
								msg.setMessage("更新资料失败!请重试！");
						}

				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
						msg.setFlag(false);
						msg.setMessage(e.getMessage());
				}
				log.info("updataReader:" + msg);
				return msg;
		}

		/*
		* 密码修改
		* */
		@ResponseBody
		@RequestMapping("updatepassword")
		public Object updatePassword(HttpServletRequest request){
				Msg<Object> msg = new Msg<>(false);
				Reader reader = (Reader) request.getSession().getAttribute("user_reader");
				String oldPassword = request.getParameter("oldPassword");
				String newPassword = request.getParameter("newPassword");
				String cfmPassword = request.getParameter("cfmPassword");
				String nickName = reader.getNickName();
				if (!readerService.checkPassword(nickName,oldPassword)){
						msg.setFlag(false);

						msg.setMessage("旧密码错误！");
						return msg;
				}
				else if (newPassword==null||newPassword.equals("")){
						msg.setFlag(false);
						msg.setMessage("新密码不能为空！");
						return msg;
				}else if(!newPassword.equals(cfmPassword)){
						msg.setFlag(false);
						msg.setMessage("两次输入密码不一样！");
						return msg;
				}
				readerService.updatePassword(oldPassword,newPassword,nickName);
				msg.setFlag(true);
				msg.setMessage("密码修改成功！");
				return msg;
		}
		/*
		 * 获取用户书架
		 * */
		@ResponseBody
		@RequestMapping("getbookshelf")
		public Msg findBookShelfByName(HttpServletRequest request) {
				Msg msg = new Msg(true);
				Reader reader = null;
				try {
						String nick_name = request.getParameter("nick_name");
						if (nick_name == null || "".equals(nick_name)) {
								msg.setFlag(false);
								msg.setMessage("无法查询用户：" + nick_name + " 的书架信息，请刷新或重新登陆！");
						} else {
								reader = readerService.findBookShelfByName(nick_name);
								if (reader != null) {
										request.getSession().setAttribute("user_reader", reader);
										msg.setData(reader);
										msg.setFlag(true);
								} else {
										msg.setFlag(false);
										msg.setMessage("找不到用户" + nick_name + "的信息，请刷新或重新登陆！");
								}
						}
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
						msg.setFlag(false);
						msg.setMessage(e.getMessage());
				}
				log.info("findBookShelfByName:" + msg);
				return msg;
		}

		/*
		 * 跳转到用户书架页面
		 * */
		@RequestMapping("personshelf")
		public String bookShelf(HttpSession session) {
				Reader reader = (Reader) session.getAttribute("user_reader");
				if (reader==null){
						return "static/unlogin";
				}
				return "bookshelf";
		}
		/*
		* 获取书架藏书
		* */
		@ResponseBody
		@RequestMapping("tobookshelflist")
		public Object getBookShelfList(HttpServletRequest request){
				Reader reader = (Reader) request.getSession().getAttribute("user_reader");
				Msg<Object> msg = new Msg<>();
				int curr = Integer.parseInt(request.getParameter("currentPage"));
				int pageSize = Integer.parseInt(request.getParameter("pageSize"));
				log.info("getConsumerRecord curr="+curr);
				log.info("getConsumerRecord pageSize="+pageSize);
				try {
						PageInfo<NovelShelf> list = readerService.getBookSelf(reader.getNickName(),curr,pageSize);
						if (list==null){
								msg.setFlag(false);
								msg.setMessage("没有找到数据！");
								return msg;
						}
						msg.setFlag(true);
						msg.setData(list);
						log.info("getBookShelfList pageInfo="+list);
				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				}
				return msg;
		}

		/*
		 * 通过id删除书架的小说
		 * */
		@RequestMapping("deletbookfromshelf")
		@ResponseBody
		public Msg deletBookFromShelf(HttpServletRequest request) {
				Msg msg = new Msg(true);
				String id = request.getParameter("id");
				Reader reader = (Reader) request.getSession().getAttribute("user_reader");
				int result = readerService.deletBookFromShelf(reader.getNickName(), Integer.parseInt(id));
				if (result != 1) {
						msg.setFlag(false);
						msg.setMessage("删除失败!请刷新后重试！");
				}
				log.info("deletBookFromShelf:" + msg);
				return msg;
		}

		/*
		 * 加入书签
		 * */
		@ResponseBody
		@RequestMapping("addbookmark")
		public Msg addBookMark(HttpServletRequest request) {
				Msg msg = new Msg(true);
				String catlogname = request.getParameter("catlogname");
				String nick_name = null;
				String book_name = request.getParameter("book_name");

				if (request.getSession().getAttribute("user_reader") != null) {
						Reader reader = (Reader) request.getSession().getAttribute("user_reader");
						nick_name = reader.getNickName();
				} else if (request.getSession().getAttribute("user_auth") != null) {
						msg.setFlag(false);
						msg.setMessage("对不起，作者账号不能添加书签哦！请切换到读者账号");
				} else {
						msg.setFlag(false);
						msg.setMessage("对不起，需要登录后才能添加书签哦！");
				}

				try {
						boolean b = false;
						if (nick_name != null) {
								b = readerService.addBookMark(nick_name, book_name, catlogname);
								String action = b ? "书签添加成功！" : "添加失败！书签以存在";
								msg.setMessage(action);
						}

				} catch (Exception e) {
						log.error("错误消息：{}", e.getMessage(), e);
				}
				log.info("addBookMark:" + msg);
				return msg;
		}

		/**
		 * 获取阅读记录
		 */
		@RequestMapping("userrecord")
		@ResponseBody
		public Object getReadRecord(String username, Integer currentPage, Integer pageSize) {
				Jedis jedis = JedisUtil.getConnect();
				Map<String, String> map = null;
				List<String> list = null;
				if (currentPage == null) {
						currentPage = 1;
				}
				if (pageSize == null) {
						pageSize = 10;
				}

				log.info("getReadRecord currentPage=" + currentPage + "   pageSize=" + pageSize);
				if (username != null && !"".equals(username)) {
						String key = "history:" + username;
						if (!jedis.exists(key)) {
								return null;
						} else {
								map = jedis.hgetAll(key);
								Collection<String> values = map.values();
								list = new ArrayList<>(values);

								list.sort((a1,a2)->{
										JSONObject json1 = JSONObject.parseObject(a1);
										JSONObject json2 = JSONObject.parseObject(a2);
										String readtime1 = json1.getString("readtime");
										String readtime2 = json2.getString("readtime");
										Date d1=null;
										Date d2=null;
										try {
												d1 = new SimpleDateFormat("yyyy-MM-dd").parse(readtime1);
												d2 = new SimpleDateFormat("yyyy-MM-dd").parse(readtime2);
										} catch (ParseException e) {
												e.printStackTrace();
										}
										return d2.compareTo(d1);
								});
						}
				}
				PageHelper.startPage(currentPage, pageSize);
				PageInfo<String> pi = new PageInfo<>();

				pi.setTotal(list.size()); // 总量
				int size = list.size() - pageSize * currentPage <= 0 ? list.size() - (pageSize * (currentPage - 1)) : pageSize;
				pi.setSize(size);//设置当前页数据量
				pi.setPageSize(pageSize);// 每页条数
				pi.setPrePage(currentPage - 1 == 0 ? 1 : currentPage - 1); // 上一页

				int pageNums = list.size() % pageSize == 0 ? list.size() / pageSize :(list.size() / pageSize) + 1; // 总页数
				pi.setPageNum(currentPage); // 当前页
				pi.setPages(pageNums); // 总页数
				pi.setNextPage(pageNums == currentPage ? pageNums : currentPage + 1); // 下一页

				//获取list指定区间数据
				list = list.subList((currentPage - 1) * pageSize, (currentPage - 1) * pageSize + size);

				pi.setList(list);
				log.info("getReadRecord pageInfo:" + pi);
				JedisUtil.close(jedis);
				return pi;
		}

		/*
		 * 获取账号余额
		 * */
		@ResponseBody
		@RequestMapping("getbalance")
		public Object getBalance(HttpSession session) {
				Msg msg = new Msg(false);
				Reader reader = (Reader) session.getAttribute("user_reader");
				if (reader == null) {
						msg.setMessage("请登录");
						msg.setData(0);
				} else {
						Float balance = readerService.getBalanceByName(reader.getNickName());
						msg.setFlag(true);
						msg.setData(balance);
				}
				return msg;
		}

		/**
		 * 单章购买
		 */
		@RequestMapping("payforone")
		@ResponseBody
		public Object payForOne(HttpServletRequest request, HttpSession session) {
				Msg<Object> msg = new Msg<>();
				String novelName = request.getParameter("novelName");
				String catalogName = request.getParameter("catalogName");
				Reader reader = (Reader) session.getAttribute("user_reader");
				if (reader == null) {
						msg.setFlag(false);
						msg.setMessage("请先登录！");
						return msg;
				}
				int result = readerService.buyOneCatalog(novelName, catalogName, reader);
				if (result == 200) {
						msg.setFlag(true);
						msg.setMessage("购买成功！");
						reader = readerService.getReaderByName(reader.getNickName());
						session.setAttribute("user_reader", reader);
				} else if (result == 400) {
						msg.setFlag(false);
						msg.setMessage("数据库错误,购买失败！");
				} else if (result == 100) {
						msg.setFlag(false);
						msg.setMessage("余额不足，请充值！");
				}
				return msg;
		}

		/**
		 * 整本购买
		 */
		@RequestMapping("payforall")
		@ResponseBody
		public Object payForAll(HttpServletRequest request, HttpSession session) {
				Msg<Object> msg = new Msg<>();
				String novelName = request.getParameter("novelName");
				Reader reader = (Reader) session.getAttribute("user_reader");
				if (reader == null) {
						msg.setFlag(false);
						msg.setMessage("请先登录！");
						return msg;
				}
				int code = readerService.buyCatalogs(reader, novelName);
				if (code == 200) {
						msg.setFlag(true);
						msg.setMessage("购买成功！");
						reader = readerService.getReaderByName(reader.getNickName());
						session.setAttribute("user_reader", reader);
				} else if (code == 400) {
						msg.setFlag(false);
						msg.setMessage("数据库错误,购买失败！");
				} else if (code == 100) {
						msg.setFlag(false);
						msg.setMessage("余额不足，请充值！");
				}
				return msg;
		}

		/**
		* 跳转到充值界面
		* */
		@RequestMapping("torecharge")
		public String toRecharge(HttpSession session){
				Reader reader = (Reader) session.getAttribute("user_reader");
				if (reader==null){
						return "static/unlogin";
				}
				return "pay/pay-list";
		}

		/**
		 * 充值成功
		* */
		@RequestMapping("/returnUrl")
		public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException {
				response.setContentType("text/html;charset=utf-8");

				boolean verifyResult = rsaCheckV1(request);
				if(verifyResult){
						//验证成功

						//商户订单号
						String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
						log.info(("pay out_trade_no="+out_trade_no));
						//支付宝交易号
						String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
						log.info(("pay trade_no="+trade_no));
						//获取充值金额
						String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
						log.info(("pay total_amount="+total_amount));
						//获取充值时间
						String timestamp = new String(request.getParameter("timestamp").getBytes("ISO-8859-1"),"UTF-8");
						log.info(("pay timestamp="+timestamp));
						String result = queryOrder(out_trade_no);
						log.info("pay result="+result);

						JSONObject json = JSONObject.parseObject(result);
						JSONObject queryResponse = json.getJSONObject("alipay_trade_query_response");
						String success = queryResponse.getString("msg");
						log.info("pay json success="+success);
						if (success.equals("Success")){

								float totalAmount =  queryResponse.getFloat("total_amount");
								Reader reader = (Reader) request.getSession().getAttribute("user_reader");
								String time = queryResponse.getString("send_pay_date");
								String remark = "歪风阅读网充值"+totalAmount +"元";

								log.info("pay json totalAmount="+totalAmount);
								log.info("pay json reader="+reader);
								log.info("pay json time="+time);
								log.info("pay json remark="+remark);

								//插入数据库
								readerService.recharge(reader,totalAmount,time,remark);
						}
						return "redirect:torecharge";

				}else{
						return "redirect:payerro";
				}
		}
		public boolean rsaCheckV1(HttpServletRequest request){
				// https://docs.open.alipay.com/54/106370
				// 获取支付宝POST过来反馈信息
				Map<String,String> params = new HashMap<>();
				Map requestParams = request.getParameterMap();
				for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
						String name = (String) iter.next();
						String[] values = (String[]) requestParams.get(name);
						String valueStr = "";
						for (int i = 0; i < values.length; i++) {
								valueStr = (i == values.length - 1) ? valueStr + values[i]
									: valueStr + values[i] + ",";
						}
						params.put(name, valueStr);
				}

				try {
						boolean verifyResult = AlipaySignature.rsaCheckV1(params,
							AlipayConfig.MERCHANT_PRIVATE_KEY,
							AlipayConfig.CHARSET,
							AlipayConfig.SIGN_TYPE);

						return verifyResult;
				} catch (AlipayApiException e) {

						return true;
				}
		}
		/*
		*查询订单
		* */
		public String  queryOrder(String outTradeNo) throws AlipayApiException {
				AlipayClient alipayClients = new DefaultAlipayClient(
					AlipayConfig.GATEWAYURL, AlipayConfig.APP_ID, AlipayConfig.MERCHANT_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
				AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
				/**请求接口*/
				alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","+"\"trade_no\":\""+ "" +"\"}");
				/**转换格式*/
				String result = alipayClients.execute(alipayRequest).getBody();
				return result;
		}
		/*
		* 充值成功
		* */
		@RequestMapping("/paysuccess")
		public String paySuccess(HttpServletRequest request,HttpServletResponse response)throws AlipayApiException{
				log.info("pay充值成功！");
				return "null";
		}
		/*
		* 充值失败
		* */
		@RequestMapping("payerro")
		public String payErro(HttpServletRequest request){
				return "static/pay_erro";
		}
		/*
		* 查询充值记录
		* */
		@RequestMapping("getrechargerecord")
		@ResponseBody
		public Object getRechargeRecord(HttpServletRequest request){
				Msg<Object> msg = new Msg<>();
				String curr = request.getParameter("currentPage");
				String pageSize = request.getParameter("pageSize");
				Reader reader = (Reader) request.getSession().getAttribute("user_reader");
				if (reader==null){
						msg.setFlag(false);
						msg.setMessage("登录过期，请重新登录后再试！");
						return msg;
				}
				PageInfo<ReaderRechargeRecord> list = readerService.getRechargeList(reader.getNickName(),
							Integer.parseInt(curr), Integer.parseInt(pageSize));
				log.info("pageInfo list="+list);
				if (list!=null){
						msg.setFlag(true);
						msg.setData(list);
				}else {
						msg.setFlag(false);
						msg.setMessage("查询错误，取与管理员联系！");
				}
				return msg;
		}

		/*
		* 查询消费记录
		* */
		@ResponseBody
		@RequestMapping("getconsumerrecord")
		public Object getConsumerRecord(HttpServletRequest request){
				Msg<Object> msg = new Msg<>();
				String curr = request.getParameter("currentPage");
				String pageSize = request.getParameter("pageSize");
				log.info("getConsumerRecord curr="+curr);
				log.info("getConsumerRecord pageSize="+pageSize);
				Reader reader = (Reader) request.getSession().getAttribute("user_reader");
				if (reader==null){
						msg.setFlag(false);
						msg.setMessage("登录过期，请重新登录后再试！");
						return msg;
				}
				PageInfo<ConsumptionRecord> list = readerService.getConsumptionList(reader.getNickName(),
						Integer.parseInt(curr), Integer.parseInt(pageSize));
				log.info("pageInfo list="+list);
				if (list!=null){
						msg.setFlag(true);
						msg.setData(list);
				}else {
						msg.setFlag(false);
						msg.setMessage("查询错误，取与管理员联系！");
				}
				return msg;
		}

		/*
		* 查询用户评论
		* */
		@RequestMapping("getcomments")
		@ResponseBody
		public Object getReaderComments(HttpServletRequest request,HttpSession session){
				Msg<Object> msg = new Msg<>(false);
				Reader reader = (Reader) session.getAttribute("user_reader");
				int currentPage = Integer.parseInt(request.getParameter("currentPage"));
				int pageSize = Integer.parseInt(request.getParameter("pageSize"));
				if (reader==null){
						msg.setFlag(false);
						msg.setMessage("请先登录再评论！");
						return msg;
				}
				//分页查询
				PageInfo<Comment> pageInfo = readerService.getComments(reader.getNickName(),currentPage,pageSize);
				log.info("查询出的pageInfo="+pageInfo);
				msg.setFlag(true);

				if (pageInfo!=null){
						msg.setData(pageInfo);
				}else {
						msg.setMessage("暂时没有评论，快去抢第一吧！");
						msg.setData(null);
				}
				return msg;
		}
		/*
		* 发表评论
		* */
		@ResponseBody
		@RequestMapping("addcomment")
		public Object addComment(HttpSession session,HttpServletRequest request){
				Msg<Object> msg = new Msg<>();
				Reader reader = (Reader) session.getAttribute("user_reader");
				String catalog = request.getParameter("catalog");
				String novelName = request.getParameter("novelName");
				String context = request.getParameter("context");
				String url = request.getParameter("url");
				if (reader==null){
						msg.setFlag(false);
						msg.setMessage("登录过期，请重新登录！");
						return msg;
				}else if(context==null||"".equals(catalog)){
						msg.setFlag(false);
						msg.setMessage("评论不能为空！");
						return msg;
				}else if(context.length()<5){
						msg.setFlag(false);
						msg.setMessage("评论不能少于5个字！");
						return msg;
				}
				int code = readerService.addComment(novelName,catalog,reader.getNickName(),context,url);
				if (code==200){
						msg.setFlag(true);
						msg.setMessage("发表评论成功!");
				}else {
						msg.setFlag(false);
						msg.setMessage("发表评论失败....");
				}
				return msg;
		}

}
